package com.mm.seguridad.service;


import com.mm.support.domain.TipoUsuario;
import com.mm.seguridad.domain.model.Usuario;
import com.mm.seguridad.domain.model.UsuarioRepository;
import com.mm.seguridad.dto.OpcionDTO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

public class MMAuthenticationProviderImpl implements MMAuthenticationProvider {

    @Autowired
    UsuarioRepository usuarioRepository;

    @Transactional
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MMAuthenticationToken token = (MMAuthenticationToken) authentication;
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        String username = (String) token.getPrincipal();
        String password = (String) token.getCredentials();
        String tokenId = (String) token.getToken();

        if (StringUtils.isNotBlank(tokenId)) {
            Integer count = usuarioRepository.existeToken(tokenId);
            if (count > 0) {
                authorities.add(new MMGrantedAuthorityImpl("ROLE_verReportePagar"));
                authorities.add(new MMGrantedAuthorityImpl("ROLE_verReporteCobrar"));
                authorities.add(new MMGrantedAuthorityImpl("ROLE_verReporteAlmacen"));
                authorities.add(new MMGrantedAuthorityImpl("ROLE_verDetalleGlobal"));
                authorities.add(new MMGrantedAuthorityImpl("ROLE_verReporteBalanceComprobacion"));
                authorities.add(new MMGrantedAuthorityImpl("ROLE_verReporteAgrupacionTipoCambio"));
                authorities.add(new MMGrantedAuthorityImpl("ROLE_verReporteRelacionado"));
                authorities.add(new MMGrantedAuthorityImpl("ROLE_USER"));
                MMAuthenticationToken MMAuthenticationToken = new MMAuthenticationToken(token.getName(),
                        token.getCredentials(),tokenId, "Invitado", -1l, TipoUsuario.INVITADO, authorities);
                return MMAuthenticationToken;
            }
        }


        Usuario usuario = usuarioRepository.findByLoginAndPassword(username, password);

        if (usuario == null) {
            return null;
        } else {
            List<OpcionDTO> opciones = OpcionManager.todasLasOpciones(usuario.getTipoUsuario().getCode());
            for (OpcionDTO opcion : opciones) {
                authorities.add(new MMGrantedAuthorityImpl("ROLE_" + opcion.getNombre()));
            }
            authorities.add(new MMGrantedAuthorityImpl("ROLE_verReportePagar"));
            authorities.add(new MMGrantedAuthorityImpl("ROLE_verReporteCobrar"));
            authorities.add(new MMGrantedAuthorityImpl("ROLE_verReporteAlmacen"));
            authorities.add(new MMGrantedAuthorityImpl("ROLE_verDetalleGlobal"));
            authorities.add(new MMGrantedAuthorityImpl("ROLE_verReporteBalanceComprobacion"));
            authorities.add(new MMGrantedAuthorityImpl("ROLE_verReporteAgrupacionTipoCambio"));
            authorities.add(new MMGrantedAuthorityImpl("ROLE_verReporteRelacionado"));
            authorities.add(new MMGrantedAuthorityImpl("ROLE_USER"));
            MMAuthenticationToken MMAuthenticationToken = new MMAuthenticationToken(token.getName(),
                    token.getCredentials(), usuario.getUsuarioId(), usuario.getGrupoEmpresarialId(), usuario.getTipoUsuario(), authorities);
            return MMAuthenticationToken;
        }
    }

    public boolean supports(Class<? extends Object> authentication) {
        return authentication.equals(MMAuthenticationToken.class);
    }


}
